package com.sitech.util.jdbc;


public class JdbcUtil
{
	private static String ORACLE = "ORACLE";
	private static String MYSQL = "mysql";
	
	
	public static String getLimitSql(String driverName,String sql, int skipResults, int maxResults)
	{
		String databaseType = getDatabaseType(driverName);
		if(ORACLE.equals(databaseType))
		{
			return oracleLimitSql(sql, skipResults, maxResults);
		}
		else if(MYSQL.equals(databaseType))
		{
			return mysqlLimitSql(sql, skipResults, maxResults);
		}
		return sql;
	}
	public static String getCountSql(String driverName,String sql)
	{
		String databaseType = getDatabaseType(driverName);
		
		if(ORACLE.equals(databaseType))
		{
			return oracleCountSql(sql);
		}
		else if(MYSQL.equals(databaseType))
		{
			return mysqlCountSql(sql);
		}
		return null;
	}
	
	
	private static String mysqlCountSql(String sql)
	{
		return null;
	}
	private static String oracleCountSql(String sql)
	{
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("select count(*) from ( ");
		sqlBuffer.append(sql);
		sqlBuffer.append(" )");
		return sqlBuffer.toString();
	}
	
	
	
	private static String oracleLimitSql(String sql, int skipResults, int maxResults)
	{
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("select * from (select row_.*, rownum rownum_ from (");
		sqlBuffer.append(sql);
		sqlBuffer.append(") row_ where rownum <=");
		sqlBuffer.append(skipResults+maxResults);
		sqlBuffer.append(") where rownum_ > ");
		sqlBuffer.append(skipResults);
		return sqlBuffer.toString();
	}
	
	private static String mysqlLimitSql(String sql, int skipResults, int maxResults)
	{
		return null;
	}
	
	private static String getDatabaseType(String driverName)
	{
		if(driverName != null)
		{
			if(driverName.toUpperCase().contains(ORACLE))
			{
				return ORACLE;
			}
		}
		return null;
	}
	
	public static boolean isSupportLimit(String driverName)
	{
		return true;
	}
}
